const UsersServices = require('../services/usersServices')
const CabinetServices = require('../services/cabinetServices')
class UsersControllers {
  constructor() {
    // 显式地将所有方法绑定到类的实例
    this.addNewUser = this.addNewUser.bind(this)
    this.delUserById = this.delUserById.bind(this)
    this.updateUserById = this.updateUserById.bind(this)
    this.getAllUsers = this.getAllUsers.bind(this)
    this.getUserById = this.getUserById.bind(this)
    this.getUserByAccount = this.getUserByAccount.bind(this)
    this.layout = this.layout.bind(this)
    this.uploadAvatar = this.uploadAvatar.bind(this)
    this.getPayQRCode = this.getPayQRCode.bind(this)
    this.banUser = this.banUser.bind(this)
    this.getUserByAccMH = this.getUserByAccMH.bind(this)
    this.releaseUser = this.releaseUser.bind(this)
    this.getUserByIdPlus = this.getUserByIdPlus.bind(this)
    this.updateUserDetailsById = this.updateUserDetailsById.bind(this)
    this.resetPwdById = this.resetPwdById.bind(this)
    this.updateMoneyById = this.updateMoneyById.bind(this)
    this.tiXian = this.tiXian.bind(this)
    this.cunJian = this.cunJian.bind(this)
    this.quJian = this.quJian.bind(this);
  }

  handleRequest = async (serviceMethod, req, res, successStatus = 200) => {
    try {
      const result = await serviceMethod(req)
      if (result.code === 0) {
        res.status(successStatus).json(result) // 成功
      } else {
        res.status(result.statusCode || 400).json(result) // 失败
      }
    } catch (error) {
      res.status(500).json({
        code: 1,
        msg: '服务器内部错误:' + error,
      })
    }
  }

   /**
   * 用户登录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
async login(req, res) {
  const { account, password } = req.body // 从请求体中获取账号和密码
  const result = await UsersServices.login(account, password)

  if (result.code === 0) {
    /* 状态异常, 禁止登录 */
    if(result.data.user.state === '0')
    {
      return res.status(403).json({
        code: 1,
        msg: ` 你已被封禁 , 请联系管理员解除!!! 封禁原因:${result.data.user.banreason}` // 返回具体原因
      })
    }
    // 状态正常 将 Token 设置到 Cookie 中
    res.cookie('token', result.data.token, {
      httpOnly: true, // 防止客户端 JavaScript 访问 Cookie
      maxAge: 60 * 60 * 60, // 过期时间（1 小时）
      secure: process.env.NODE_ENV === 'production', // 在生产环境中启用 HTTPS
      sameSite: 'strict', // 防止 CSRF 攻击
    })
    // 返回登录成功信息（不返回 Token）
    res.status(200).json({
      result
    })
  } else {
    res.status(result.statusCode || 400).json(result) // 失败
  }
}

    /**
   * 用户退出登录
   * @param {Object} req - 请求对象
   * @param {Object} res - 响应对象
   */
  async layout(req, res) {
    try {
      // 清除客户端的 Cookie
      res.clearCookie('token')

      // 返回成功响应
      res.status(200).json({
        msg: '退出登录成功',
      })
    } catch (error) {
      res.status(400).json({ e: error.message })
    }
  }

  /**
   * 用户注册
   * @param {*} req 
   * @param {*} res 
   */
  async addNewUser(req, res) {
    const { nickname, account, password } = req.body

    // 校验昵称是否为空
  if (!nickname.length) {
    return res.status(404).json({
      code: 0,
      msg: '昵称不能为空',
    })
  }

  // 校验账号和密码长度是否大于等于6
  if (account.length < 6 || password.length < 6) {
    return res.status(404).json({
      code: 0,
      msg: '账号和密码长度都必须大于等于6',
    })
  }

  // 校验账号是否包含中文
  const chineseRegex = /[\u4e00-\u9fa5]/;
  if (chineseRegex.test(account)) {
    return res.status(404).json({
      code: 0,
      msg: '账号不能包含中文',
    })
  }

    // 如果校验通过，继续处理请求
    await this.handleRequest(
      () => UsersServices.addNewUser(req.body),
      req,
      res,
      201
    )
  }

  async delUserById(req, res) {
    await this.handleRequest(
      () => UsersServices.delUserById(req.params.id),
      req,
      res,
      200
    )
  }

  async updateUserById(req, res) {
    await this.handleRequest(
      () => UsersServices.updateUserById(req.params.id, req.body),
      req,
      res
    )
  }

  async getAllUsers(req, res) {
    await this.handleRequest(
      () => UsersServices.getAllUsers(),
      req,
      res
    )
  }

  async getUserById(req, res) {
    await this.handleRequest(
      () => UsersServices.getUserById(req.params.id),
      req,
      res
    )
  }

  async getUserByAccount(req, res) {
    await this.handleRequest(
      () => UsersServices.getUserByAccount(req.params.acc),
      req,
      res
    )
  }

  async uploadAvatar(req, res) {
    const { id, avatarUrl } = req.body
    await this.handleRequest(
      () => UsersServices.uploadAvatar(id, avatarUrl),
      req,
      res
    )
  }

  async getPayQRCode(req, res) {
  await this.handleRequest(
    () => UsersServices.getPayQRCode(),
    req,
    res
  )
}
/* 封禁用户 */
async banUser(req, res) {
  const { id, banreason } = req.body
  await this.handleRequest(
    () => UsersServices.banUser(id, banreason),
    req,
    res
  )
}
/* 模糊查询 */
async getUserByAccMH(req, res) {
  await this.handleRequest(
  () => UsersServices.getUserByAccMH(req.params.account),
  req,
  res
  )
}
/* 解封用户 */
async releaseUser(req, res) {
  await this.handleRequest(
    () => UsersServices.releaseUser(req.params.id),
    req,
    res
  )
}
/* 管理员根据ID获取用户全部信息 */
async getUserByIdPlus(req, res) {
  await this.handleRequest(
    () => UsersServices.getUserById(req.params.id),
    req,
    res
  )
}
/* 更新用户详细信息 */
async updateUserDetailsById(req, res) {
  await this.handleRequest(
    () => UsersServices.updateUserDetailsById(req.params.id, req.body),
    req,
    res
  )
}
/* 修改用户密码 */
async resetPwdById(req, res) {
  const user = await UsersServices.getUserById(req.params.id)
  if(!user)
    res.status(403).json({ msg: '用户不存在' })
  await this.handleRequest(
    () => UsersServices.resetPwdById(req.params.id, req.body),
    req,
    res
  )
}
/* 充值接口  */
async updateMoneyById(req, res) {
  const { userId, amount, orderNum } = req.body
  await this.handleRequest(
    () => UsersServices.updateMoneyById(userId, amount, orderNum),
    req,
    res
  )
}
/* 提现接口 */
async tiXian(req, res) {
  const { id, amount, orderNum } = req.body
  await this.handleRequest(
    () => UsersServices.tiXian(id, amount, orderNum),
    req,
    res
  )
}
/* 存件:  开门 修改对应快递柜状态 生成订单 发送站内信提醒用户 */
async cunJian(req, res) {
  const { cunId, quId, cabinetNum, cabinetBelong } = req.body;
  // 简化实现是否合法
  const cabinet = await CabinetServices.getCabinetByBelongAndNum(
    cabinetBelong,
    cabinetNum
  );
  // 如果目标柜状态不合法(非空闲 或 未关门)
  if (
    cabinet.data.dataValues.state !== "0" ||
    cabinet.data.dataValues.isclosed !== "1"
  )
    res.status(400).json({ code: 0, msg: "目标柜状态不合法" });
  // 如果目标柜状态不合法(非空闲 或 未关门)
  else
    await this.handleRequest(
      () => UsersServices.cunJian(cunId, quId, cabinetNum, cabinetBelong),
      req,
      res
    );
}
/* 取件: 获取取件码 去 cabinets 表中根据取件码找快递柜 找到了开门结算订单 找不到提示用户 */ 
async quJian(req, res) {
  //简化实现,不判断了
  await this.handleRequest(
    () => UsersServices.quJian(req.params.quCode),
    req,
    res
  )
}
}

module.exports = new UsersControllers()